package com.etonedu.meals.service;

import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.LogUtils;
import com.etonedu.meals.bean.MachineTimeBean;
import com.etonedu.meals.bean.Result;
import com.etonedu.meals.bean.ScreenTimeBean;
import com.etonedu.meals.common.SPConst;
import com.etonedu.meals.dao.DaoUtils;
import com.etonedu.meals.enumeration.APICodeEnum;
import com.etonedu.meals.enumeration.MessageEnum;
import com.etonedu.meals.http.IGetUrl;
import com.etonedu.meals.http.LogReportUtils;
import com.etonedu.meals.http.ParamsUtils;
import com.etonedu.meals.http.Request;
import com.etonedu.meals.http.xutils.NewXUtilsRequest;
import com.etonedu.meals.http.xutils.NewXUtilsResponse;
import com.etonedu.meals.machine.DeviceUtils;
import com.etonedu.meals.machine.OperationMachine;
import com.etonedu.meals.machine.OperationSrceen;
import com.etonedu.meals.utils.SharedPreferencesUtil;
import com.etonedu.meals.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.xutils.http.HttpMethod;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

import io.objectbox.Box;

public class MachineService extends Service {

    private SharedPreferencesUtil spu;
    private MachineTimeBean timeBean;

    private Handler handler = new Handler();
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        spu = SharedPreferencesUtil.getInstance(this);

        init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Subscribe
    public void onEvent(String msg) {
        if ("心跳".equals(msg)) {

            long startTime = spu.getLong(SPConst.START_MACHINE_TIME);
            long endTime = spu.getLong(SPConst.END_MACHINE_TIME);

            if (endTime > 0) {
                long time = System.currentTimeMillis();
                long offTime = endTime;

                offTime = offTime + 60 * 1000;

                String model = Build.MODEL;
                if (offTime < time) {// 关机时间小于当前时间
                    LogUtils.e("关机时间小于当前时间");
                    if (!"rk3288".equals(model)) {
                        DeviceUtils.clearMachine();

                    }

                    String startTimeStr = Utils.timestamp2String1(startTime, "yyyy-MM-dd-HH-mm");
                    String endTimeStr = Utils.timestamp2String1(endTime, "yyyy-MM-dd-HH-mm");

                    String time1 = Utils.timestamp2String1(time, "yyyy-MM-dd HH:mm:ss");
                    String pagek = this.getClass().getPackage().getName();

                    LogUtils.e("没有定时关机,重新设置开关机时间,关机时间:" + endTimeStr + ",开机时间:" + startTimeStr);
                    LogReportUtils.log("没有定时关机,重新设置开关机时间,关机时间:" + endTimeStr + ",开机时间:" + startTimeStr, pagek, Utils.getLineInfo(), time1);
                    DeviceUtils.clearMachineTime(x.app());

                    MachineTimeBean t = new MachineTimeBean();
                    t.setOnTime(startTime);
                    t.setOffTime(endTime);
                    t.setOnDate(startTimeStr);
                    t.setOffDate(endTimeStr);
                    OperationMachine.setOnOffMachine(t);

                    DeviceUtils.closeMachine();
                    DeviceUtils.shutdown(x.app());
                }
            }
        }
    }

    @Subscribe
    public void refresh(MessageEnum messageEnum) {
        String type = messageEnum.getType();
        SharedPreferencesUtil spu = SharedPreferencesUtil.getInstance(this);
        String token = spu.getString(SPConst.TOKEN);
        LogUtils.e(type);
        if (MessageEnum.ECB_2015.getType().equals(type)) {//开关机时间段更新
            getMachineUrl(token);
        } else if (MessageEnum.ECB_2016.getType().equals(type)) {//开关屏时间段更新
            getScreenUrl(token);
        } else if (MessageEnum.ECB_2017.getType().equals(type)) {
            String model = Build.MODEL;

            if (timeBean != null) {
                DeviceUtils.setOnOffMachineV2(timeBean);
            }

            DeviceUtils.closeMachine();
            DeviceUtils.shutdown(x.app());

        } else if (MessageEnum.NONE.getType().equals(type)) {
            getMachineUrl(token);
            getScreenUrl(token);
        }
    }

    private void init() {
        String token = spu.getString(SPConst.TOKEN);

        getMachineUrl(token);
        getScreenUrl(token);
    }

    private void getMachineUrl(String token) {
        String apiCode = APICodeEnum.agw30161012.getApiCode();
        String type = spu.getString(SPConst.ENVIRONMENT);
//        String environType = EnvironmentType.TEST01.getType();

        String url = spu.getString(SPConst.AGW_30161012);
        if (!Utils.isEmpty(url)) {
            getMachineData(url,token);
            return;
        }
        Request request = new Request();
        request.getPublicUrl(apiCode,type);
        request.setGetUrl(new IGetUrl() {
            @Override
            public void success(String content) {
                spu.setString(SPConst.AGW_30161012,content);
                getMachineData(content,token);
                LogUtils.e("content = "+content);
            }

            @Override
            public void fail(String content) {
                LogUtils.e("content = "+content);
            }
        });
    }

    private void getMachineData(String url,String token) {

        String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
        String pagek = this.getClass().getPackage().getName();
        LogReportUtils.log("获取开关机时间,",pagek,Utils.getLineInfo(),time1);

        String apiCode = APICodeEnum.agw30161012.getApiCode();
        String header = ParamsUtils.getHeader(apiCode, token);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("deviceCode", Utils.getDevCode());
        hashMap.put("currentTime", System.currentTimeMillis());
        hashMap.put("dayNum",60);
        Gson gson = new Gson();
        String json = gson.toJson(hashMap);

        String data = ParamsUtils.getEncrypt(apiCode,json);

        String data1 = ParamsUtils.getParams(apiCode,data);

        NewXUtilsRequest request = new NewXUtilsRequest(header, data1);
        request.requet(url, apiCode, HttpMethod.POST, new NewXUtilsResponse(){

            @Override
            public void response(String type, String result) {
                LogUtils.e("result = "+result);

                Type typeToken = new TypeToken<Result>() {
                }.getType();
                Gson gson = new Gson();
                Result r = gson.fromJson(result, typeToken);

                String data = r.getData();

                if (!Utils.isEmpty(data)) {
                    String deData = ParamsUtils.getDecrypt(apiCode, data);
//                LogUtils.e("deData = "+deData);
                    LogUtils.json(deData);
                    LogReportUtils.log("开关机时间列表:"+deData,pagek,Utils.getLineInfo(),time1);
                    Type machineType = new TypeToken<List<MachineTimeBean>>() {
                    }.getType();
                    List<MachineTimeBean> list = gson.fromJson(deData, machineType);

                    addMachineDB(list);
                } else {
                    spu.setLong(SPConst.START_MACHINE_TIME,0);
                    spu.setLong(SPConst.END_MACHINE_TIME,0);
                }
            }

            @Override
            public void error(String type, String msg) {
                LogUtils.e("msg = "+msg);
            }
        });
    }

    private void getScreenUrl(String token) {
        String apiCode = APICodeEnum.agw30161013.getApiCode();
        String type = spu.getString(SPConst.ENVIRONMENT);
//        String environType = EnvironmentType.TEST01.getType();

        String url = spu.getString(SPConst.AGW_30161013);
        if (!Utils.isEmpty(url)) {
            getScreenData(url,token);
            return;
        }

        Request request = new Request();
        request.getPublicUrl(apiCode,type);
        request.setGetUrl(new IGetUrl() {
            @Override
            public void success(String content) {
                spu.setString(SPConst.AGW_30161013,content);
                getScreenData(content,token);
                LogUtils.e("content = "+content);
            }

            @Override
            public void fail(String content) {
                LogUtils.e("content = "+content);
            }
        });
    }

    private void getScreenData(String url,String token) {

        String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
        String pagek = this.getClass().getPackage().getName();
        LogReportUtils.log("获取开关屏时间,",pagek,Utils.getLineInfo(),time1);
        String apiCode = APICodeEnum.agw30161013.getApiCode();
        String header = ParamsUtils.getHeader(apiCode, token);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("deviceCode", Utils.getDevCode());
        hashMap.put("currentTime", System.currentTimeMillis());
        hashMap.put("dayNum",60);
        Gson gson = new Gson();
        String json = gson.toJson(hashMap);

        String data = ParamsUtils.getEncrypt(apiCode,json);

        String data1 = ParamsUtils.getParams(apiCode,data);

        NewXUtilsRequest request = new NewXUtilsRequest(header, data1);
        request.requet(url, apiCode, HttpMethod.POST, new NewXUtilsResponse(){

            @Override
            public void response(String type, String result) {
                LogUtils.e("result = "+result);

                Type typeToken = new TypeToken<Result>() {
                }.getType();
                Gson gson = new Gson();
                Result r = gson.fromJson(result, typeToken);

                String data = r.getData();

                if (!Utils.isEmpty(data)) {
                    String deData = ParamsUtils.getDecrypt(apiCode, data);
//                LogUtils.e("deData = "+deData);
                    LogUtils.json(deData);
                    LogReportUtils.log("开关屏时间列表:"+deData,pagek,Utils.getLineInfo(),time1);
                    Type screenType = new TypeToken<List<ScreenTimeBean>>() {
                    }.getType();
                    List<ScreenTimeBean> list = gson.fromJson(deData, screenType);

                    addScreenDB(list);
                }
            }

            @Override
            public void error(String type, String msg) {
                LogUtils.e("msg = "+msg);
            }
        });
    }

    private void addMachineDB(List<MachineTimeBean> list) {
        int flag = spu.getInt(SPConst.CLOSE_DEV);
        if (flag == 1) return;
        if (!Utils.listIsNullOrEmpty(list)) {

            Box<MachineTimeBean> box = DaoUtils.getBoxMachineTimeBean();
            box.removeAll();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Looper.prepare();
                        box.put(list);

                        DaoUtils.delletLtCurrTime4MachineTimeBean();
                        List<MachineTimeBean> timeBeanList = box.getAll();
                        if (!Utils.listIsNullOrEmpty(timeBeanList)) {
                            // 设置开关机时间
                            MachineTimeBean mtb = timeBeanList.get(0);

                            String model = Build.MODEL;
                            if (!"rk3288".equals(model)) {
                                DeviceUtils.clearMachine();

                            }
                            DeviceUtils.clearMachineTime(x.app());
                            timeBean = mtb;

                            OperationMachine.setOnOffMachine(mtb);

                            String content = "服务器设置的时间：" + "关机时间：" + mtb.getOffDate() + "，开机时间：" + mtb.getOnDate();
                            LogReportUtils.logReportPublicUrl("", "5", "1", content);
                        } else {
                            box.removeAll();

                            timeBean = null;

                            String model = Build.MODEL;
                            if (!"rk3288".equals(model)) {
                                DeviceUtils.clearMachine();

                            }
                            DeviceUtils.clearMachineTime(x.app());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            try {
                Box<MachineTimeBean> box = DaoUtils.getBoxMachineTimeBean();
                box.removeAll();
                DeviceUtils.clearMachine();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void addScreenDB(List<ScreenTimeBean> list) {
        if (!Utils.listIsNullOrEmpty(list)) {

            Box<ScreenTimeBean> box = DaoUtils.getBoxScreenTimeBean();
            box.removeAll();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Looper.prepare();
                        box.put(list);

                        DaoUtils.delletScreenDaoLtCurrTime();
                        List<ScreenTimeBean> timeBeans = box.getAll();
                        if (!Utils.listIsNullOrEmpty(timeBeans)) {
                            ScreenTimeBean stb = timeBeans.get(0);
                            OperationSrceen.setScreen(stb);
                        } else {
                            box.removeAll();
                            OperationSrceen.cancelScreen();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            try {
                Box<ScreenTimeBean> box = DaoUtils.getBoxScreenTimeBean();
                box.removeAll();
                OperationSrceen.cancelScreen();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
